<?php

namespace addons\News\api\modules\v1\controllers;

use Yii;
use yii\data\ActiveDataProvider;
use api\controllers\OnAuthController;
use common\enums\StatusEnum;
use addons\News\common\models\News;

/**
 * 默认控制器
 *
 * Class DefaultController
 * @package addons\News\api\modules\v1\controllers
 */
class DefaultController extends OnAuthController
{
    public $modelClass = News::class;

    /**
    * 不用进行登录验证的方法
    *
    * 例如： ['index', 'update', 'create', 'view', 'delete']
    * 默认全部需要验证
    *
    * @var array
    */
    protected $authOptional = ['index', 'view'];

    /**
    * 首页
    *
    * @return string
    */
    public function actionIndex()
    {
        return new ActiveDataProvider([
            'query' => $this->modelClass::find()
                ->select('*')
                ->where(['status' => StatusEnum::ENABLED])
                ->andFilterWhere(['cate_id' => Yii::$app->request->get('cate_id')])
                ->andFilterWhere(['merchant_id' => Yii::$app->user->identity->merchant_id])
                ->orderBy('sort asc, id desc')
                ->with('cate')
                ->asArray(),
            'pagination' => [
                'pageSize' => $this->pageSize,
                'validatePage' => false,// 超出分页不返回data
            ],
        ]);
    }
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $model::updateAll(['view' => $model->view+1]);
        return $model;
    }

    /**
     * 权限验证
     *
     * @param string $action 当前的方法
     * @param null $model 当前的模型类
     * @param array $params $_GET变量
     * @throws \yii\web\BadRequestHttpException
     */
    public function checkAccess($action, $model = null, $params = [])
    {
        // 方法名称
        if (in_array($action, ['delete', 'create', 'update'])) {
            throw new \yii\web\BadRequestHttpException('权限不足');
        }
    }
}